const os = require("node:os");
const fs = require("node:fs");

const projectConfigPath = os.homedir() + "/public-ip-dynamic/"
const logPath = projectConfigPath + "log/"
if (!fs.existsSync(projectConfigPath)) {
    fs.mkdirSync(projectConfigPath);
}
if (!fs.existsSync(logPath)){
    fs.mkdirSync(logPath);
}

function resolveMessage(topic, type ,message, date) {
    const dateString = `${date.getFullYear()}-${fillTimePos(date.getMonth() + 1)}-${fillTimePos(date.getDate())} ${fillTimePos(date.getHours())}:${fillTimePos(date.getMinutes())}:${fillTimePos(date.getSeconds())}`;
    return `${dateString} [${topic}] ${type} ${message}`;
}

function nowDay(date) {
    return `${date.getFullYear()}-${fillTimePos(date.getMonth() + 1)}-${fillTimePos(date.getDate())}`
}

function fillTimePos(time) {
    if (time < 10) {
        return `0${time}`
    }
    return time
}

function log(topic, message) {
    const date = new Date()
    fs.appendFile(logPath + nowDay(date) + '-log', resolveMessage(topic, 'INFO', message, date) + '\n', 'utf-8', err => {
        if (err){
            console.error(err)
        }
    })
    console.log(resolveMessage(topic, 'INFO', message, date))
}

function error(topic, message) {
    const date = new Date()
    fs.appendFile(logPath + nowDay(date) + '-log', resolveMessage(topic, 'ERROR', message, date) + '\n', 'utf-8', err => {
        if (err) {
            console.error(err)
        }
    })
    console.log(resolveMessage(topic, 'ERROR', message, date))
}

module.exports = {
    basicPath: projectConfigPath,
    info: log,
    error: error
}


